import axios, { AxiosRequestConfig, AxiosError } from "axios";
import { message } from "antd";

type CustomResponse<T> = Promise<[boolean, T]>;

interface ErrorResponse {
  message: string;
  statusCode: number;
}

const request = axios.create({
  baseURL: import.meta.env.VITE_SERVER_HOST,
  timeout: 5000,
});

// 请求拦截器（可选）
request.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Authorization = token;
  }

  return config;
});

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const newToken = response.headers.token;
    if (newToken) {
      localStorage.setItem("token", newToken);
    }

    return response.data;
  },
  (error) => {
    if (!error.response) {
      return Promise.reject(error);
    }
    const { data } = error.response;
    if (data.statusCode === 401) {
      message.error("登录过期，请重新登录");
      setTimeout(() => {
        window.location.href = "/login";
      }, 1500);
    } else {
      return Promise.reject(error);
    }
  }
);

export const customRequest = async <T>(
  option: AxiosRequestConfig
): CustomResponse<T> => {
  try {
    const res = await request(option);
    return [true, res.data as T];
  } catch (error) {
    const axiosError = error as AxiosError<ErrorResponse>;
    const errorData = axiosError.response?.data || null;
    const errorMessage = errorData?.message || axiosError.message;
    message.error(errorMessage);
    return [false, errorData as T];
  }
};

export default request;
